package com.network.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.network.vo.Result;
import com.network.vo.SecurityUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author peng
 */
@Component("myAuthenctiationSuccessHandler")
public class LoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler
{


    private final static Logger logger = LoggerFactory.getLogger(LoginSuccessHandler.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        RequestCache requestCache = new HttpSessionRequestCache();
        SecurityUser userDetails = (SecurityUser) authentication.getPrincipal();

        logger.info("登录用户user:" + userDetails.getUsername() + "login"+request.getContextPath());

        Result<SecurityUser> result=new Result<>();
        result.setCode(200);
        result.setMsg("登录成功");
        result.setData(userDetails);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(new Gson().toJson(result));

    }



}
